from msg import *;
import yaml;
from configuration import *;
#from msgpasser import configfile;
import sys;

class configfile1:
    configRout=None;
    configFile=None;

    def __init__(self, configRout):
        #print configRout
        configFileDescriptor = open(configRout,'r');
        try:
            self.configFile = yaml.load(configFileDescriptor);
        except yaml.YAMLError:
            print "error in configuration file";

    def getConfiguration(self):
        return self.configFile['configuration'];




#http://www.python.org/doc/essays/graphs.html
def find_shortest_path(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return path
    if not graph.has_key(start):
        return None
    shortest = None
    for node in graph[start]:
        if node not in path:
            newpath = find_shortest_path(graph, node, end, path)
            if newpath:
                if not shortest or len(newpath) < len(shortest):
                    shortest = newpath
    return shortest

def nextHop(G, start, end):
    shortestPath = find_shortest_path(G, start, end)
    if len(shortestPath) > 1:
        return shortestPath[1]
    else:
        return "BAD"

def getForwardingTable(yamlUrl, source):

    myConfigFile = configfile(yamlUrl)
    configuration = myConfigFile.getConfiguration()
    graph = {};
    table = {};
    for data in configuration:
        graph[data['name']] = data['group']
    for data in configuration:
        if(data['name'] != source):
            table[data['name']] = nextHop(graph, source, data['name'])
    #print table
    return table

def get_node_neighbors(yamlUrl, node):

    myConfigFile = configfile1(yamlUrl)
    configuration = myConfigFile.getConfiguration()
    graph = {};
    table = {};
    for data in configuration:
        if(data['name'] == node):
            return data['group']
    return 0

getForwardingTable('demo.yaml', 'b')
